package com.by.gatewayhelper.token;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
@Component("wxcpsidebarTokenHelper")
public class WxCpSidebarTokenHelper implements TokenHelper {

    @Value("${token.secret.wxcpsidebar}")
    private String encryptKey;

    private AES aes;

    @EventListener(ApplicationStartedEvent.class)
    public void initEncrypt(ApplicationStartedEvent event) {
        aes = SecureUtil.aes(encryptKey.getBytes(StandardCharsets.UTF_8));
    }

    @Override
    public String createToken(Map<String, String> tokenInfo) {
        return aes.encryptHex(xor(JSON.toJSONString(tokenInfo)), StandardCharsets.UTF_8);
    }

    @Override
    public boolean verifyToken(String token) {
        try {
            xor(aes.decryptStr(token, StandardCharsets.UTF_8));
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public JSONObject analyzeToken(String token) {
        String content = xor(aes.decryptStr(token, StandardCharsets.UTF_8));
        return JSONObject.parseObject(content);
    }

}
